home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1996 May: Tool Chest / Developer CD Series May 1996 (Tool Chest) (Apple Computer) (1996).iso / Sample Code / Macintosh Sample Code / SC.002.TESample / TESample.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-18  |  41.1 KB  |  1,301 lines  |  [TEXT/MPS ]

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple TextEdit Sample Application
  6. #
  7. #    TESample
  8. #
  9. #    This file: TESample.c    -    C Source (main segment)
  10. #
  11. #    Copyright © 1989 Apple Computer, Inc.
  12. #    All rights reserved.
  13. #
  14. #    Versions:
  15. #                1.00                08/88
  16. #                1.01                11/88
  17. #                1.02                04/89
  18. #                1.03                06/89
  19. #                1.04                06/92
  20. #
  21. #    Components:
  22. #                TESample.p            June 1, 1989
  23. #                TESample.c            June 1, 1989
  24. #                TESampleInit.c        June 4, 1992
  25. #                TESampleGlue.a        June 1, 1989
  26. #                TESample.r            June 1, 1989
  27. #                TESample.h            June 1, 1989
  28. #                PTESample.make        June 1, 1989
  29. #                CTESample.make        June 1, 1989
  30. #                TCTESample.π        June 4, 1992
  31. #                TCTESample.π.rsrc    June 4, 1992
  32. #                TCTESampleGlue.c    June 4, 1992
  33. #
  34. #    TESample is an example application that demonstrates how 
  35. #    to initialize the commonly used toolbox managers, operate 
  36. #    successfully under MultiFinder, handle desk accessories and 
  37. #    create, grow, and zoom windows. The fundamental TextEdit 
  38. #    toolbox calls and TextEdit autoscroll are demonstrated. It 
  39. #    also shows how to create and maintain scrollbar controls.
  40. #
  41. #    It does not by any means demonstrate all the techniques you 
  42. #    need for a large application. In particular, Sample does not 
  43. #    cover exception handling, multiple windows/documents, 
  44. #    sophisticated memory management, printing, or undo. All of 
  45. #    these are vital parts of a normal full-sized application.
  46. #
  47. #    This application is an example of the form of a Macintosh 
  48. #    application; it is NOT a template. It is NOT intended to be 
  49. #    used as a foundation for the next world-class, best-selling, 
  50. #    600K application. A stick figure drawing of the human body may 
  51. #    be a good example of the form for a painting, but that does not 
  52. #    mean it should be used as the basis for the next Mona Lisa.
  53. #
  54. #    We recommend that you review this program or Sample before 
  55. #    beginning a new application. Sample is a simple app. which doesn’t 
  56. #    use TextEdit or the Control Manager.
  57. #
  58. ------------------------------------------------------------------------------*/
  59.  
  60.  
  61. /* Segmentation strategy:
  62.  
  63.    This program consists of three segments.
  64.    1. "Main" contains most of the code, including the MPW libraries, and the
  65.       main program.  This segment is in the file Sample.c
  66.    2. "Initialize" contains code that is only used once, during startup, and
  67.       can be unloaded after the program starts.  This segment is in the file
  68.       SampleInit.c.
  69.    3. "%A5Init" is automatically created by the Linker to initialize globals
  70.       for the MPW libraries and is unloaded right away. */
  71.  
  72.  
  73. /* SetPort strategy:
  74.  
  75.    Toolbox routines do not change the current port. In spite of this, in this
  76.    program we use a strategy of calling SetPort whenever we want to draw or
  77.    make calls which depend on the current port. This makes us less vulnerable
  78.    to bugs in other software which might alter the current port (such as the
  79.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  80.    Hopefully, this also makes the routines from this program more self-contained,
  81.    since they don't depend on the current port setting. */
  82.  
  83.  
  84. /* Clipboard strategy:
  85.  
  86.    This program does not maintain a private scrap. Whenever a cut, copy, or paste
  87.    occurs, we import/export from the public scrap to TextEdit's scrap right away,
  88.    using the TEToScrap and TEFromScrap routines. If we did use a private scrap,
  89.    the import/export would be in the activate/deactivate event and suspend/resume
  90.    event routines. */
  91.  
  92. /* A/UX is case sensitive, so use correct case for include file names */
  93. #include <Limits.h>
  94. #include <types.h>
  95. #include <quickdraw.h>
  96. #include <fonts.h>
  97. #include <events.h>
  98. #include <controls.h>
  99. #include <windows.h>
  100. #include <menus.h>
  101. #include <textedit.h>
  102. #include <dialogs.h>
  103. #include <desk.h>
  104. #include <scrap.h>
  105. #include <toolutils.h>
  106. #include <memory.h>
  107. #include <segload.h>
  108. #include <files.h>
  109. #include <osutils.h>
  110. #ifndef AUX
  111. #  include <diskinit.h>
  112. #endif
  113. #include <packages.h>
  114. #include "TESample.h"        /* bring in all the #defines for TESample */
  115. #include <traps.h>
  116.  
  117. /* A/UX C understands neither #pragma, nor segments, so don't pragma */
  118. #ifndef AUX
  119.   #pragma segment Main
  120. #endif
  121.  
  122.  
  123. /* A DocumentRecord contains the WindowRecord for one of our document windows,
  124.    as well as the TEHandle for the text we are editing. Other document fields
  125.    can be added to this record as needed. For a similar example, see how the
  126.    Window Manager and Dialog Manager add fields after the GrafPort. */
  127. typedef struct {
  128.     WindowRecord    docWindow;
  129.     TEHandle        docTE;
  130.     ControlHandle    docVScroll;
  131.     ControlHandle    docHScroll;
  132.     TEClickLoopUPP    docClick;
  133. } DocumentRecord, *DocumentPeek;
  134.  
  135.  
  136.  
  137. /* The "g" prefix is used to emphasize that a variable is global. */
  138.  
  139. /* GMac is used to hold the result of a SysEnvirons call. This makes
  140.    it convenient for any routine to check the environment. It is
  141.    global information, anyway. */
  142. SysEnvRec    gMac;                /* set up by Initialize */
  143.  
  144. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  145.    trap is available. If it is false, we know that we must call GetNextEvent. */
  146. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  147.  
  148. /* GInBackground is maintained by our OSEvent handling routines. Any part of
  149.    the program can check it to find out if it is currently in the background. */
  150. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  151.  
  152. /* GNumDocuments is used to keep track of how many open documents there are
  153.    at any time. It is maintained by the routines that open and close documents. */
  154. short        gNumDocuments;        /* maintained by Initialize, DoNew, and DoCloseWindow */
  155.  
  156.  
  157. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  158.    dependency on the ordering of fields within a Rect */
  159. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  160. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  161.  
  162.  
  163.  
  164. /* This routine is part of the MPW runtime library. This external
  165.    reference to it is done so that we can unload its segment, %A5Init. */
  166.  
  167. #if !(THINK_C | AUX)
  168.   extern void _DataInit();
  169. #endif
  170.  
  171.  
  172. /* A reference to our assembly language routine that gets attached to the clickLoop
  173. field of our TE record. */
  174.  
  175. #ifdef AUX
  176. extern void AsmClickLoop();
  177. #else
  178. extern pascal void AsmClickLoop();
  179. #endif
  180.  
  181. TEClickLoopUPP gClickLoopUPP = NewTEClickLoopProc(AsmClickLoop);
  182.  
  183. main()
  184. {
  185. #if !(THINK_C | AUX)
  186.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  187. #endif
  188.     
  189.     /* 1.01 - call to ForceEnvirons removed */
  190.     
  191.     /*    If you have stack requirements that differ from the default,
  192.         then you could use SetApplLimit to increase StackSpace at 
  193.         this point, before calling MaxApplZone. */
  194.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  195.  
  196.     Initialize();                    /* initialize the program */
  197. #ifndef AUX
  198.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  199. #endif
  200.  
  201.     EventLoop();                    /* call the main event loop */
  202. }
  203.  
  204.  
  205. /* Get events forever, and handle them by calling DoEvent.
  206.    Also call AdjustCursor each time through the loop. */
  207.  
  208. void EventLoop()
  209. {
  210.     RgnHandle    cursorRgn;
  211.     Boolean        gotEvent;
  212.     EventRecord    event;
  213.     Point        mouse;
  214.  
  215.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  216.     do {
  217.         /* use WNE if it is available */
  218.         if ( gHasWaitNextEvent ) {
  219.             GetGlobalMouse(&mouse);
  220.             AdjustCursor(mouse, cursorRgn);
  221.             gotEvent = WaitNextEvent(everyEvent, &event, GetSleep(), cursorRgn);
  222.         }
  223.         else {
  224.             SystemTask();
  225.             gotEvent = GetNextEvent(everyEvent, &event);
  226.         }
  227.         if ( gotEvent ) {
  228.             /* make sure we have the right cursor before handling the event */
  229.             AdjustCursor(event.where, cursorRgn);
  230.             DoEvent(&event);
  231.         }
  232.         else
  233.             DoIdle();                /* perform idle tasks when it’s not our event */
  234.         /*    If you are using modeless dialogs that have editText items,
  235.             you will want to call IsDialogEvent to give the caret a chance
  236.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  237.             for a non-NIL value before calling IsDialogEvent. */
  238.     } while ( true );    /* loop forever; we quit via ExitToShell */
  239. } /*EventLoop*/
  240.  
  241.  
  242. /* Do the right thing for an event. Determine what kind of event it is, and call
  243.  the appropriate routines. */
  244.  
  245. void DoEvent(EventRecord *event)
  246. {
  247.     short        part, err;
  248.     WindowPtr    window;
  249.     char        key;
  250.     Point        aPoint;
  251.  
  252.     switch ( event->what ) {
  253.         case nullEvent:
  254.             /* we idle for null/mouse moved events ands for events which aren’t
  255.                 ours (see EventLoop) */
  256.             DoIdle();
  257.             break;
  258.         case mouseDown:
  259.             part = FindWindow(event->where, &window);
  260.             switch ( part ) {
  261.                 case inMenuBar:             /* process a mouse menu command (if any) */
  262.                     AdjustMenus();    /* bring ’em up-to-date */
  263.                     DoMenuCommand(MenuSelect(event->where));
  264.                     break;
  265.                 case inSysWindow:           /* let the system handle the mouseDown */
  266.                     SystemClick(event, window);
  267.                     break;
  268.                 case inContent:
  269.                     if ( window != FrontWindow() ) {
  270.                         SelectWindow(window);
  271.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  272.                     } else
  273.                         DoContentClick(window, event);
  274.                     break;
  275.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  276.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  277.                     break;
  278.                 case inGoAway:
  279.                     if ( TrackGoAway(window, event->where) )
  280.                         DoCloseWindow(window); /* we don’t care if the user cancelled */
  281.                     break;
  282.                 case inGrow:
  283.                     DoGrowWindow(window, event);
  284.                     break;
  285.                 case inZoomIn:
  286.                 case inZoomOut:
  287.                 if ( TrackBox(window, event->where, part) )
  288.                         DoZoomWindow(window, part);
  289.                     break;
  290.             }
  291.             break;
  292.         case keyDown:
  293.         case autoKey:                       /* check for menukey equivalents */
  294.             key = event->message & charCodeMask;
  295.             if ( event->modifiers & cmdKey ) {    /* Command key down */
  296.                 if ( event->what == keyDown ) {
  297.                     AdjustMenus();            /* enable/disable/check menu items properly */
  298.                     DoMenuCommand(MenuKey(key));
  299.                 }
  300.             } else
  301.                 DoKeyDown(event);
  302.             break;
  303.         case activateEvt:
  304.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  305.             break;
  306.         case updateEvt:
  307.             DoUpdate((WindowPtr) event->message);
  308.             break;
  309.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  310.             to a diskEvt, so that the user can format a floppy. */
  311.         case diskEvt:
  312. #ifndef AUX
  313.             if ( HiWord(event->message) != noErr ) {
  314.                 SetPt(&aPoint, kDILeft, kDITop);
  315.                 err = DIBadMount(aPoint, event->message);
  316.             }
  317. #endif
  318.             break;
  319.         case kOSEvent:
  320.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  321.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  322.                 case kMouseMovedMessage:
  323.                     DoIdle();                    /* mouse-moved is also an idle event */
  324.                     break;
  325.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  326.                     gInBackground = (event->message & kResumeMask) == 0;
  327.                     DoActivate(FrontWindow(), !gInBackground);
  328.                     break;
  329.             }
  330.             break;
  331.     }
  332. } /*DoEvent*/
  333.  
  334.  
  335. /*    Change the cursor's shape, depending on its position. This also calculates the region
  336.     where the current cursor resides (for WaitNextEvent). When the mouse moves outside of
  337.     this region, an event is generated. If there is more to the event than just
  338.     “the mouse moved”, we get called before the event is processed to make sure
  339.     the cursor is the right one. In any (ahem) event, this is called again before we
  340.     fall back into WNE. */
  341.  
  342. void AdjustCursor(Point mouse, RgnHandle region)
  343. {
  344.     WindowPtr    window;
  345.     RgnHandle    arrowRgn;
  346.     RgnHandle    iBeamRgn;
  347.     Rect        iBeamRect;
  348.  
  349.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  350.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  351.         /* calculate regions for different cursor shapes */
  352.         arrowRgn = NewRgn();
  353.         iBeamRgn = NewRgn();
  354.  
  355.         /* start arrowRgn wide open */
  356.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  357.  
  358.         /* calculate iBeamRgn */
  359.         if ( IsAppWindow(window) ) {
  360.             iBeamRect = (*((DocumentPeek) window)->docTE)->viewRect;
  361.             SetPort(window);    /* make a global version of the viewRect */
  362.             LocalToGlobal(&TopLeft(iBeamRect));
  363.             LocalToGlobal(&BotRight(iBeamRect));
  364.             RectRgn(iBeamRgn, &iBeamRect);
  365.             /* we temporarily change the port’s origin to “globalfy” the visRgn */
  366.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  367.             SectRgn(iBeamRgn, window->visRgn, iBeamRgn);
  368.             SetOrigin(0, 0);
  369.         }
  370.  
  371.         /* subtract other regions from arrowRgn */
  372.         DiffRgn(arrowRgn, iBeamRgn, arrowRgn);
  373.  
  374.         /* change the cursor and the region parameter */
  375.         if ( PtInRgn(mouse, iBeamRgn) ) {
  376.             SetCursor(*GetCursor(iBeamCursor));
  377.             CopyRgn(iBeamRgn, region);
  378.         } else {
  379.             SetCursor(&qd.arrow);
  380.             CopyRgn(arrowRgn, region);
  381.         }
  382.  
  383.         DisposeRgn(arrowRgn);
  384.         DisposeRgn(iBeamRgn);
  385.     }
  386. } /*AdjustCursor*/
  387.  
  388.  
  389. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  390.     it will return either a pending event or a null event. In either case,
  391.     the where field of the event record will contain the current position
  392.     of the mouse in global coordinates and the modifiers field will reflect
  393.     the current state of the modifiers. Another way to get the global
  394.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  395.     being sure that thePort is set to a valid port. */
  396.  
  397. void GetGlobalMouse(Point *mouse)
  398. {
  399.     EventRecord    event;
  400.     
  401.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  402.     *mouse = event.where;                /* just the mouse position */
  403. } /*GetGlobalMouse*/
  404.  
  405.  
  406. /*    Called when a mouseDown occurs in the grow box of an active window. In
  407.     order to eliminate any 'flicker', we want to invalidate only what is
  408.     necessary. Since ResizeWindow invalidates the whole portRect, we save
  409.     the old TE viewRect, intersect it with the new TE viewRect, and
  410.     remove the result from the update region. However, we must make sure
  411.     that any old update region that might have been around gets put back. */
  412.  
  413. void DoGrowWindow(WindowPtr window, EventRecord *event)
  414. {
  415.     long        growResult;
  416.     Rect        tempRect;
  417.     RgnHandle    tempRgn;
  418.     DocumentPeek doc;
  419.     
  420.     tempRect = qd.screenBits.bounds;                    /* set up limiting values */
  421.     tempRect.left = kMinDocDim;
  422.     tempRect.top = kMinDocDim;
  423.     growResult = GrowWindow(window, event->where, &tempRect);
  424.     /* see if it really changed size */
  425.     if ( growResult != 0 ) {
  426.         doc = (DocumentPeek) window;
  427.         tempRect = (*doc->docTE)->viewRect;                /* save old text box */
  428.         tempRgn = NewRgn();
  429.         GetLocalUpdateRgn(window, tempRgn);                /* get localized update region */
  430.         SizeWindow(window, LoWord(growResult), HiWord(growResult), true);
  431.         ResizeWindow(window);
  432.         /* calculate & validate the region that hasn’t changed so it won’t get redrawn */
  433.         SectRect(&tempRect, &(*doc->docTE)->viewRect, &tempRect);
  434.         ValidRect(&tempRect);                            /* take it out of update */
  435.         InvalRgn(tempRgn);                                /* put back any prior update */
  436.         DisposeRgn(tempRgn);
  437.     }
  438. } /* DoGrowWindow */
  439.  
  440.  
  441. /*     Called when a mouseClick occurs in the zoom box of an active window.
  442.     Everything has to get re-drawn here, so we don't mind that
  443.     ResizeWindow invalidates the whole portRect. */
  444.  
  445. void DoZoomWindow(WindowPtr window, short part)
  446. {
  447.     EraseRect(&window->portRect);
  448.     ZoomWindow(window, part, window == FrontWindow());
  449.     ResizeWindow(window);
  450. } /*  DoZoomWindow */
  451.  
  452.  
  453. /* Called when the window has been resized to fix up the controls and content. */
  454. void ResizeWindow(WindowPtr window)
  455. {
  456.     AdjustScrollbars(window, true);
  457.     AdjustTE(window);
  458.     InvalRect(&window->portRect);
  459. } /* ResizeWindow */
  460.  
  461.  
  462. /* Returns the update region in local coordinates */
  463. void GetLocalUpdateRgn(WindowPtr window, RgnHandle localRgn)
  464. {
  465.     CopyRgn(((WindowPeek) window)->updateRgn, localRgn);    /* save old update region */
  466.     OffsetRgn(localRgn, window->portBits.bounds.left, window->portBits.bounds.top);
  467. } /* GetLocalUpdateRgn */
  468.  
  469.  
  470. /*    This is called when an update event is received for a window.
  471.     It calls DrawWindow to draw the contents of an application window.
  472.     As an efficiency measure that does not have to be followed, it
  473.     calls the drawing routine only if the visRgn is non-empty. This
  474.     will handle situations where calculations for drawing or drawing
  475.     itself is very time-consuming. */
  476.  
  477. void DoUpdate(WindowPtr window)
  478. {
  479.     if ( IsAppWindow(window) ) {
  480.         BeginUpdate(window);                /* this sets up the visRgn */
  481.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  482.             DrawWindow(window);
  483.         EndUpdate(window);
  484.     }
  485. } /*DoUpdate*/
  486.  
  487.  
  488. /*    This is called when a window is activated or deactivated.
  489.     It calls TextEdit to deal with the selection. */
  490.  
  491. void DoActivate(WindowPtr window, Boolean becomingActive)
  492. {
  493.     RgnHandle    tempRgn, clipRgn;
  494.     Rect        growRect;
  495.     DocumentPeek doc;
  496.     
  497.     if ( IsAppWindow(window) ) {
  498.         doc = (DocumentPeek) window;
  499.         if ( becomingActive ) {
  500.             /*    since we don’t want TEActivate to draw a selection in an area where
  501.                 we’re going to erase and redraw, we’ll clip out the update region
  502.                 before calling it. */
  503.             tempRgn = NewRgn();
  504.             clipRgn = NewRgn();
  505.             GetLocalUpdateRgn(window, tempRgn);            /* get localized update region */
  506.             GetClip(clipRgn);
  507.             DiffRgn(clipRgn, tempRgn, tempRgn);            /* subtract updateRgn from clipRgn */
  508.             SetClip(tempRgn);
  509.             TEActivate(doc->docTE);
  510.             SetClip(clipRgn);                            /* restore the full-blown clipRgn */
  511.             DisposeRgn(tempRgn);
  512.             DisposeRgn(clipRgn);
  513.             
  514.             /* the controls must be redrawn on activation: */
  515.             (*doc->docVScroll)->contrlVis = kControlVisible;
  516.             (*doc->docHScroll)->contrlVis = kControlVisible;
  517.             InvalRect(&(*doc->docVScroll)->contrlRect);
  518.             InvalRect(&(*doc->docHScroll)->contrlRect);
  519.             /* the growbox needs to be redrawn on activation: */
  520.             growRect = window->portRect;
  521.             /* adjust for the scrollbars */
  522.             growRect.top = growRect.bottom - kScrollbarAdjust;
  523.             growRect.left = growRect.right - kScrollbarAdjust;
  524.             InvalRect(&growRect);
  525.         }
  526.         else {        
  527.             TEDeactivate(doc->docTE);
  528.             /* the controls must be hidden on deactivation: */
  529.             HideControl(doc->docVScroll);
  530.             HideControl(doc->docHScroll);
  531.             /* the growbox should be changed immediately on deactivation: */
  532.             DrawGrowIcon(window);
  533.         }
  534.     }
  535. } /*DoActivate*/
  536.  
  537.  
  538. /*    This is called when a mouseDown occurs in the content of a window. */
  539.  
  540. void DoContentClick(WindowPtr window, EventRecord *event)
  541. {
  542.     Point        mouse;
  543.     ControlHandle control;
  544.     short        part, value;
  545.     Boolean        shiftDown;
  546.     DocumentPeek doc;
  547.     Rect        teRect;
  548.  
  549.     if ( IsAppWindow(window) ) {
  550.         SetPort(window);
  551.         mouse = event->where;                            /* get the click position */
  552.         GlobalToLocal(&mouse);
  553.         doc = (DocumentPeek) window;
  554.         /* see if we are in the viewRect. if so, we won’t check the controls */
  555.         GetTERect(window, &teRect);
  556.         if ( PtInRect(mouse, &teRect) ) {
  557.             /* see if we need to extend the selection */
  558.             shiftDown = (event->modifiers & shiftKey) != 0;    /* extend if Shift is down */
  559.             TEClick(mouse, shiftDown, doc->docTE);
  560.         } else {
  561.             part = FindControl(mouse, window, &control);
  562.             switch ( part ) {
  563.                 case 0:                            /* do nothing for viewRect case */
  564.                     break;
  565.                 case inThumb:
  566.                     value = GetControlValue(control);
  567.                     part = TrackControl(control, mouse, nil);
  568.                     if ( part != 0 ) {
  569.                         value -= GetControlValue(control);
  570.                         /* value now has CHANGE in value; if value changed, scroll */
  571.                         if ( value != 0 )
  572.                             if ( control == doc->docVScroll )
  573.                                 TEScroll(0, value * (*doc->docTE)->lineHeight, doc->docTE);
  574.                             else
  575.                                 TEScroll(value, 0, doc->docTE);
  576.                     }
  577.                     break;
  578.                 default:                        /* they clicked in an arrow, so track & scroll */
  579.                     {
  580.                         ControlActionUPP upp;
  581.                         if ( control == doc->docVScroll )
  582.                             upp = NewControlActionProc(VActionProc);
  583.                         else
  584.                             upp = NewControlActionProc(HActionProc);
  585.                         value = TrackControl(control, mouse, upp);
  586.                         DisposeRoutineDescriptor(upp);
  587.                     }
  588.                     break;
  589.             }
  590.         }
  591.     }
  592. } /*DoContentClick*/
  593.  
  594.  
  595. /* This is called for any keyDown or autoKey events, except when the
  596.  Command key is held down. It looks at the frontmost window to decide what
  597.  to do with the key typed. */
  598.  
  599. void DoKeyDown(EventRecord *event)
  600. {
  601.     WindowPtr    window;
  602.     char        key;
  603.     TEHandle    te;
  604.  
  605.     window = FrontWindow();
  606.     if ( IsAppWindow(window) ) {
  607.         te = ((DocumentPeek) window)->docTE;
  608.         key = event->message & charCodeMask;
  609.         /* we have a char. for our window; see if we are still below TextEdit’s
  610.             limit for the number of characters (but deletes are always rad) */
  611.         if ( key == kDelChar ||
  612.                 (*te)->teLength - ((*te)->selEnd - (*te)->selStart) + 1 <
  613.                 kMaxTELength ) {
  614.             TEKey(key, te);
  615.             AdjustScrollbars(window, false);
  616.             AdjustTE(window);
  617.         } else
  618.             AlertUser(eExceedChar);
  619.     }
  620. } /*DoKeyDown*/
  621.  
  622.  
  623. /*    Calculate a sleep value for WaitNextEvent. This takes into account the things
  624.     that DoIdle does with idle time. */
  625.  
  626. unsigned long GetSleep()
  627. {
  628.     long        sleep;
  629.     WindowPtr    window;
  630.     TEHandle    te;
  631.  
  632.     sleep = LONG_MAX;                        /* default value for sleep */
  633.     if ( !gInBackground ) {
  634.         window = FrontWindow();            /* and the front window is ours... */
  635.         if ( IsAppWindow(window) ) {
  636.             te = ((DocumentPeek) (window))->docTE;    /* and the selection is an insertion point... */
  637.             if ( (*te)->selStart == (*te)->selEnd )
  638.                 sleep = GetCaretTime();        /* blink time for the insertion point */
  639.         }
  640.     }
  641.     return sleep;
  642. } /*GetSleep*/
  643.  
  644.  
  645. /*    Common algorithm for pinning the value of a control. It returns the actual amount
  646.     the value of the control changed. Note the pinning is done for the sake of returning
  647.     the amount the control value changed. */
  648.  
  649. void CommonAction(ControlHandle control, short *amount)
  650. {
  651.     short        value, max;
  652.     
  653.     value = GetControlValue(control);    /* get current value */
  654.     max = GetControlMaximum(control);        /* and maximum value */
  655.     *amount = value - *amount;
  656.     if ( *amount < 0 )
  657.         *amount = 0;
  658.     else if ( *amount > max )
  659.         *amount = max;
  660.     SetControlValue(control, *amount);
  661.     *amount = value - *amount;        /* calculate the real change */
  662. } /* CommonAction */
  663.  
  664.  
  665. /* Determines how much to change the value of the vertical scrollbar by and how
  666.     much to scroll the TE record. */
  667.  
  668. #ifndef AUX
  669.    pascal void VActionProc(ControlHandle control, short part)
  670. #else
  671.    void CVActionProc(ControlHandle control, short part)
  672. #endif
  673. {
  674.     short        amount;
  675.     WindowPtr    window;
  676.     TEPtr        te;
  677.     
  678.     if ( part != 0 ) {                /* if it was actually in the control */
  679.         window = (*control)->contrlOwner;
  680.         te = *((DocumentPeek) window)->docTE;
  681.         switch ( part ) {
  682.             case inUpButton:
  683.             case inDownButton:        /* one line */
  684.                 amount = 1;
  685.                 break;
  686.             case inPageUp:            /* one page */
  687.             case inPageDown:
  688.                 amount = (te->viewRect.bottom - te->viewRect.top) / te->lineHeight;
  689.                 break;
  690.         }
  691.         if ( (part == inDownButton) || (part == inPageDown) )
  692.             amount = -amount;        /* reverse direction for a downer */
  693.         CommonAction(control, &amount);
  694.         if ( amount != 0 )
  695.             TEScroll(0, amount * te->lineHeight, ((DocumentPeek) window)->docTE);
  696.     }
  697. } /* VActionProc */
  698.  
  699.  
  700. /* Determines how much to change the value of the horizontal scrollbar by and how
  701. much to scroll the TE record. */
  702.  
  703. #ifndef AUX
  704.    pascal void HActionProc(ControlHandle control, short part)
  705. #else
  706.    void CHActionProc(ControlHandle control, short part)
  707. #endif
  708. {
  709.     short        amount;
  710.     WindowPtr    window;
  711.     TEPtr        te;
  712.     
  713.     if ( part != 0 ) {
  714.         window = (*control)->contrlOwner;
  715.         te = *((DocumentPeek) window)->docTE;
  716.         switch ( part ) {
  717.             case inUpButton:
  718.             case inDownButton:        /* a few pixels */
  719.                 amount = kButtonScroll;
  720.                 break;
  721.             case inPageUp:            /* a page */
  722.             case inPageDown:
  723.                 amount = te->viewRect.right - te->viewRect.left;
  724.                 break;
  725.         }
  726.         if ( (part == inDownButton) || (part == inPageDown) )
  727.             amount = -amount;        /* reverse direction */
  728.         CommonAction(control, &amount);
  729.         if ( amount != 0 )
  730.             TEScroll(amount, 0, ((DocumentPeek) window)->docTE);
  731.     }
  732. } /* VActionProc */
  733.  
  734.  
  735. /* This is called whenever we get a null event et al.
  736.  It takes care of necessary periodic actions. For this program, it calls TEIdle. */
  737.  
  738. void DoIdle()
  739. {
  740.     WindowPtr    window;
  741.  
  742.     window = FrontWindow();
  743.     if ( IsAppWindow(window) )
  744.         TEIdle(((DocumentPeek) window)->docTE);
  745. } /*DoIdle*/
  746.  
  747.  
  748. /* Draw the contents of an application window. */
  749.  
  750. void DrawWindow(WindowPtr window)
  751. {
  752.     SetPort(window);
  753.     EraseRect(&window->portRect);
  754.     DrawControls(window);
  755.     DrawGrowIcon(window);
  756.     TEUpdate(&window->portRect, ((DocumentPeek) window)->docTE);
  757. } /*DrawWindow*/
  758.  
  759.  
  760. /*    Enable and disable menus based on the current state.
  761.     The user can only select enabled menu items. We set up all the menu items
  762.     before calling MenuSelect or MenuKey, since these are the only times that
  763.     a menu item can be selected. Note that MenuSelect is also the only time
  764.     the user will see menu items. This approach to deciding what enable/
  765.     disable state a menu item has the advantage of concentrating all
  766.     the decision-making in one routine, as opposed to being spread throughout
  767.     the application. Other application designs may take a different approach
  768.     that may or may not be as valid. */
  769.  
  770. void AdjustMenus()
  771. {
  772.     WindowPtr    window;
  773.     MenuHandle    menu;
  774.     long        offset;
  775.     Boolean        undo;
  776.     Boolean        cutCopyClear;
  777.     Boolean        paste;
  778.     TEHandle    te;
  779.  
  780.     window = FrontWindow();
  781.  
  782.     menu = GetMenuHandle(mFile);
  783.     if ( gNumDocuments < kMaxOpenDocuments )
  784.         EnableItem(menu, iNew);        /* New is enabled when we can open more documents */
  785.     else
  786.         DisableItem(menu, iNew);
  787.     if ( window != nil )            /* Close is enabled when there is a window to close */
  788.         EnableItem(menu, iClose);
  789.     else
  790.         DisableItem(menu, iClose);
  791.  
  792.     menu = GetMenuHandle(mEdit);
  793.     undo = false;
  794.     cutCopyClear = false;
  795.     paste = false;
  796.     if ( IsDAWindow(window) ) {
  797.         undo = true;                /* all editing is enabled for DA windows */
  798.         cutCopyClear = true;
  799.         paste = true;
  800.     } else if ( IsAppWindow(window) ) {
  801.         te = ((DocumentPeek) window)->docTE;
  802.         if ( (*te)->selStart < (*te)->selEnd )
  803.             cutCopyClear = true;
  804.             /* Cut, Copy, and Clear is enabled for app. windows with selections */
  805.         if ( GetScrap(nil, 'TEXT', &offset)  > 0)
  806.             paste = true;            /* if there’s any text in the clipboard, paste is enabled */
  807.     }
  808.     if ( undo )
  809.         EnableItem(menu, iUndo);
  810.     else
  811.         DisableItem(menu, iUndo);
  812.     if ( cutCopyClear ) {
  813.         EnableItem(menu, iCut);
  814.         EnableItem(menu, iCopy);
  815.         EnableItem(menu, iClear);
  816.     } else {
  817.         DisableItem(menu, iCut);
  818.         DisableItem(menu, iCopy);
  819.         DisableItem(menu, iClear);
  820.     }
  821.     if ( paste )
  822.         EnableItem(menu, iPaste);
  823.     else
  824.         DisableItem(menu, iPaste);
  825. } /*AdjustMenus*/
  826.  
  827.  
  828. /*    This is called when an item is chosen from the menu bar (after calling
  829.     MenuSelect or MenuKey). It does the right thing for each command. */
  830.  
  831. void DoMenuCommand(long menuResult)
  832. {
  833.     short        menuID, menuItem;
  834.     short        itemHit, daRefNum;
  835.     Str255        daName;
  836.     OSErr        saveErr;
  837.     TEHandle    te;
  838.     WindowPtr    window;
  839.     Handle        aHandle;
  840.     long        oldSize, newSize;
  841.     long        total, contig;
  842.  
  843.     window = FrontWindow();
  844.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  845.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  846.     switch ( menuID ) {
  847.         case mApple:
  848.             switch ( menuItem ) {
  849.                 case iAbout:        /* bring up alert for About */
  850.                     itemHit = Alert(rAboutAlert, nil);
  851.                     break;
  852.                 default:            /* all non-About items in this menu are DAs et al */
  853.                     /* type Str255 is an array in MPW 3 */
  854.                     GetMenuItemText(GetMenuHandle(mApple), menuItem, daName);
  855.                     daRefNum = OpenDeskAcc(daName);
  856.                     break;
  857.             }
  858.             break;
  859.         case mFile:
  860.             switch ( menuItem ) {
  861.                 case iNew:
  862.                     DoNew();
  863.                     break;
  864.                 case iClose:
  865.                     DoCloseWindow(FrontWindow());            /* ignore the result */
  866.                     break;
  867.                 case iQuit:
  868.                     Terminate();
  869.                     break;
  870.             }
  871.             break;
  872.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  873.             if ( !SystemEdit(menuItem-1) ) {
  874.                 te = ((DocumentPeek) FrontWindow())->docTE;
  875.                 switch ( menuItem ) {
  876.                     case iCut:
  877.                         if ( ZeroScrap() == noErr ) {
  878. #ifndef AUX
  879.                             PurgeSpace(&total, &contig);
  880.                             if ((*te)->selEnd - (*te)->selStart + kTESlop > contig)
  881.                                 AlertUser(eNoSpaceCut);
  882.                             else 
  883. #endif
  884.                                 {
  885.                                 TECut(te);
  886.                                 if ( TEToScrap() != noErr ) {
  887.                                     AlertUser(eNoCut);
  888.                                     ZeroScrap();
  889.                                 }
  890.                             }
  891.                         }
  892.                         break;
  893.                     case iCopy:
  894.                         if ( ZeroScrap() == noErr ) {
  895.                             TECopy(te);    /* after copying, export the TE scrap */
  896.                             if ( TEToScrap() != noErr ) {
  897.                                 AlertUser(eNoCopy);
  898.                                 ZeroScrap();
  899.                             }
  900.                         }
  901.                         break;
  902.                     case iPaste:    /* import the TE scrap before pasting */
  903.                         if ( TEFromScrap() == noErr ) {
  904.                             if ( TEGetScrapLength() + ((*te)->teLength -
  905.                                 ((*te)->selEnd - (*te)->selStart)) > kMaxTELength )
  906.                                 AlertUser(eExceedPaste);
  907.                             else {
  908.                                 aHandle = (Handle) TEGetText(te);
  909.                                 oldSize = GetHandleSize(aHandle);
  910.                                 newSize = oldSize + TEGetScrapLength() + kTESlop;
  911.                                 SetHandleSize(aHandle, newSize);
  912.                                 saveErr = MemError();
  913.                                 SetHandleSize(aHandle, oldSize);
  914.                                 if (saveErr != noErr)
  915.                                     AlertUser(eNoSpacePaste);
  916.                                 else
  917.                                     TEPaste(te);
  918.                             }
  919.                         }
  920.                         else
  921.                             AlertUser(eNoPaste);
  922.                         break;
  923.                     case iClear:
  924.                         TEDelete(te);
  925.                         break;
  926.                 }
  927.             AdjustScrollbars(window, false);
  928.             AdjustTE(window);
  929.             }
  930.             break;
  931.     }
  932.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  933. } /*DoMenuCommand*/
  934.  
  935.  
  936. /* Create a new document and window. */
  937.  
  938. void DoNew()
  939. {
  940.     Boolean        good;
  941.     Ptr            storage;
  942.     WindowPtr    window;
  943.     Rect        destRect, viewRect;
  944.     DocumentPeek doc;
  945.  
  946.     storage = NewPtr(sizeof(DocumentRecord));
  947.     if ( storage != nil ) {
  948.         window = GetNewWindow(rDocWindow, storage, (WindowPtr) -1);
  949.         if ( window != nil ) {
  950.             gNumDocuments += 1;            /* this will be decremented when we call DoCloseWindow */
  951.             good = false;
  952.             SetPort(window);
  953.             doc =  (DocumentPeek) window;
  954.             GetTERect(window, &viewRect);
  955.             destRect = viewRect;
  956.             destRect.right = destRect.left + kMaxDocWidth;
  957.             doc->docTE = TENew(&destRect, &viewRect);
  958.             good = doc->docTE != nil;    /* if TENew succeeded, we have a good document */
  959.             if ( good ) {                /* 1.02 - good document? — proceed */
  960.                 AdjustViewRect(doc->docTE);
  961.                 TEAutoView(true, doc->docTE);
  962.                 doc->docClick = (*doc->docTE)->clickLoop;
  963.                 (*doc->docTE)->clickLoop = gClickLoopUPP;
  964.             }
  965.             
  966.             if ( good ) {                /* good document? — get scrollbars */
  967.                 doc->docVScroll = GetNewControl(rVScroll, window);
  968.                 good = (doc->docVScroll != nil);
  969.             }
  970.             if ( good) {
  971.                 doc->docHScroll = GetNewControl(rHScroll, window);
  972.                 good = (doc->docHScroll != nil);
  973.             }
  974.             
  975.             if ( good ) {                /* good? — adjust & draw the controls, draw the window */
  976.                 /* false to AdjustScrollValues means musn’t redraw; technically, of course,
  977.                 the window is hidden so it wouldn’t matter whether we called ShowControl or not. */
  978.                 AdjustScrollValues(window, false);
  979.                 ShowWindow(window);
  980.             } else {
  981.                 DoCloseWindow(window);    /* otherwise regret we ever created it... */
  982.                 AlertUser(eNoWindow);            /* and tell user */
  983.             }
  984.         } else
  985.             DisposePtr(storage);            /* get rid of the storage if it is never used */
  986.     }
  987. } /*DoNew*/
  988.  
  989.  
  990. /* Close a window. This handles desk accessory and application windows. */
  991.  
  992. /*    1.01 - At this point, if there was a document associated with a
  993.     window, you could do any document saving processing if it is 'dirty'.
  994.     DoCloseWindow would return true if the window actually closed, i.e.,
  995.     the user didn’t cancel from a save dialog. This result is handy when
  996.     the user quits an application, but then cancels the save of a document
  997.     associated with a window. */
  998.  
  999. Boolean DoCloseWindow(WindowPtr window)
  1000. {
  1001.     TEHandle    te;
  1002.  
  1003.     if ( IsDAWindow(window) )
  1004.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  1005.     else if ( IsAppWindow(window) ) {
  1006.         te = ((DocumentPeek) window)->docTE;
  1007.         if ( te != nil )
  1008.             TEDispose(te);            /* dispose the TEHandle if we got far enough to make one */
  1009.         /*    1.01 - We used to call DisposeWindow, but that was technically
  1010.             incorrect, even though we allocated storage for the window on
  1011.             the heap. We should instead call CloseWindow to have the structures
  1012.             taken care of and then dispose of the storage ourselves. */
  1013.         CloseWindow(window);
  1014.         DisposePtr((Ptr) window);
  1015.         gNumDocuments -= 1;
  1016.     }
  1017.     return true;
  1018. } /*DoCloseWindow*/
  1019.  
  1020.  
  1021. /**************************************************************************************
  1022. *** 1.01 DoCloseBehind(window) was removed ***
  1023.  
  1024.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  1025.     and not having to worry about updating the windows, but it suffered
  1026.     from a fatal flaw. If a desk accessory owned two windows, it would
  1027.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  1028.     got around to calling DoCloseWindow for that other window that was already
  1029.     closed, things would go very poorly. Another option would be to have a
  1030.     procedure, GetRearWindow, that would go through the window list and return
  1031.     the last window. Instead, we decided to present the standard approach
  1032.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  1033.     has a potential benefit in that the window whose document needs to be saved
  1034.     may be visible since it is the front window, therefore decreasing the
  1035.     chance of user confusion. For aesthetic reasons, the windows in the
  1036.     application should be checked for updates periodically and have the
  1037.     updates serviced.
  1038. **************************************************************************************/
  1039.  
  1040.  
  1041. /* Clean up the application and exit. We close all of the windows so that
  1042.  they can update their documents, if any. */
  1043.  
  1044. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  1045.     shell, but will return instead. */
  1046.  
  1047. void Terminate()
  1048. {
  1049.     WindowPtr    aWindow;
  1050.     Boolean        closed;
  1051.     
  1052.     closed = true;
  1053.     do {
  1054.         aWindow = FrontWindow();                /* get the current front window */
  1055.         if (aWindow != nil)
  1056.             closed = DoCloseWindow(aWindow);    /* close this window */    
  1057.     }
  1058.     while (closed && (aWindow != nil));
  1059.     if (closed)
  1060.         ExitToShell();                            /* exit if no cancellation */
  1061. } /*Terminate*/
  1062.  
  1063.  
  1064. /* Return a rectangle that is inset from the portRect by the size of
  1065.     the scrollbars and a little extra margin. */
  1066.  
  1067. void GetTERect(WindowPtr window, Rect *teRect)
  1068. {
  1069.     *teRect = window->portRect;
  1070.     InsetRect(teRect, kTextMargin, kTextMargin);    /* adjust for margin */
  1071.     teRect->bottom = teRect->bottom - 15;        /* and for the scrollbars */
  1072.     teRect->right = teRect->right - 15;
  1073. } /*GetTERect*/
  1074.  
  1075.  
  1076. /* Update the TERec's view rect so that it is the greatest multiple of
  1077.     the lineHeight that still fits in the old viewRect. */
  1078.  
  1079. void AdjustViewRect(TEHandle docTE)
  1080. {
  1081.     TEPtr        te;
  1082.     
  1083.     te = *docTE;
  1084.     te->viewRect.bottom = (((te->viewRect.bottom - te->viewRect.top) / te->lineHeight)
  1085.                             * te->lineHeight) + te->viewRect.top;
  1086. } /*AdjustViewRect*/
  1087.  
  1088.  
  1089. /* Scroll the TERec around to match up to the potentially updated scrollbar
  1090.     values. This is really useful when the window has been resized such that the
  1091.     scrollbars became inactive but the TERec was already scrolled. */
  1092.  
  1093. void AdjustTE(WindowPtr window)
  1094. {
  1095.     TEPtr        te;
  1096.     
  1097.     te = *((DocumentPeek)window)->docTE;
  1098.     TEScroll((te->viewRect.left - te->destRect.left) -
  1099.             GetControlValue(((DocumentPeek)window)->docHScroll),
  1100.             (te->viewRect.top - te->destRect.top) -
  1101.                 (GetControlValue(((DocumentPeek)window)->docVScroll) *
  1102.                 te->lineHeight),
  1103.             ((DocumentPeek)window)->docTE);
  1104. } /*AdjustTE*/
  1105.  
  1106.  
  1107. /* Calculate the new control maximum value and current value, whether it is the horizontal or
  1108.     vertical scrollbar. The vertical max is calculated by comparing the number of lines to the
  1109.     vertical size of the viewRect. The horizontal max is calculated by comparing the maximum document
  1110.     width to the width of the viewRect. The current values are set by comparing the offset between
  1111.     the view and destination rects. If necessary and we canRedraw, have the control be re-drawn by
  1112.     calling ShowControl. */
  1113.  
  1114. void AdjustHV(Boolean isVert, ControlHandle control, TEHandle docTE, Boolean canRedraw)
  1115. {
  1116.     short        value, lines, max;
  1117.     short        oldValue, oldMax;
  1118.     TEPtr        te;
  1119.     
  1120.     oldValue = GetControlValue(control);
  1121.     oldMax = GetControlMaximum(control);
  1122.     te = *docTE;                            /* point to TERec for convenience */
  1123.     if ( isVert ) {
  1124.         lines = te->nLines;
  1125.         /* since nLines isn’t right if the last character is a return, check for that case */
  1126.         if ( *(*te->hText + te->teLength - 1) == kCrChar )
  1127.             lines += 1;
  1128.         max = lines - ((te->viewRect.bottom - te->viewRect.top) /
  1129.                 te->lineHeight);
  1130.     } else
  1131.         max = kMaxDocWidth - (te->viewRect.right - te->viewRect.left);
  1132.     
  1133.     if ( max < 0 ) max = 0;
  1134.     SetControlMaximum(control, max);
  1135.     
  1136.     /* Must deref. after SetControlMaximum since, technically, it could draw and therefore move
  1137.         memory. This is why we don’t just do it once at the beginning. */
  1138.     te = *docTE;
  1139.     if ( isVert )
  1140.         value = (te->viewRect.top - te->destRect.top) / te->lineHeight;
  1141.     else
  1142.         value = te->viewRect.left - te->destRect.left;
  1143.     
  1144.     if ( value < 0 ) value = 0;
  1145.     else if ( value >  max ) value = max;
  1146.     
  1147.     SetControlValue(control, value);
  1148.     /* now redraw the control if it needs to be and can be */
  1149.     if ( canRedraw || (max != oldMax) || (value != oldValue) )
  1150.         ShowControl(control);
  1151. } /*AdjustHV*/
  1152.  
  1153.  
  1154. /* Simply call the common adjust routine for the vertical and horizontal scrollbars. */
  1155.  
  1156. void AdjustScrollValues(WindowPtr window, Boolean canRedraw)
  1157. {
  1158.     DocumentPeek doc;
  1159.     
  1160.     doc = (DocumentPeek)window;
  1161.     AdjustHV(true, doc->docVScroll, doc->docTE, canRedraw);
  1162.     AdjustHV(false, doc->docHScroll, doc->docTE, canRedraw);
  1163. } /*AdjustScrollValues*/
  1164.  
  1165.  
  1166. /*    Re-calculate the position and size of the viewRect and the scrollbars.
  1167.     kScrollTweek compensates for off-by-one requirements of the scrollbars
  1168.     to have borders coincide with the growbox. */
  1169.  
  1170. void AdjustScrollSizes(WindowPtr window)
  1171. {
  1172.     Rect        teRect;
  1173.     DocumentPeek doc;
  1174.     
  1175.     doc = (DocumentPeek) window;
  1176.     GetTERect(window, &teRect);                            /* start with TERect */
  1177.     (*doc->docTE)->viewRect = teRect;
  1178.     AdjustViewRect(doc->docTE);                            /* snap to nearest line */
  1179.     MoveControl(doc->docVScroll, window->portRect.right - kScrollbarAdjust, -1);
  1180.     SizeControl(doc->docVScroll, kScrollbarWidth, (window->portRect.bottom - 
  1181.                 window->portRect.top) - (kScrollbarAdjust - kScrollTweek));
  1182.     MoveControl(doc->docHScroll, -1, window->portRect.bottom - kScrollbarAdjust);
  1183.     SizeControl(doc->docHScroll, (window->portRect.right - 
  1184.                 window->portRect.left) - (kScrollbarAdjust - kScrollTweek),
  1185.                 kScrollbarWidth);
  1186. } /*AdjustScrollSizes*/
  1187.  
  1188.  
  1189. /* Turn off the controls by jamming a zero into their contrlVis fields (HideControl erases them
  1190.     and we don't want that). If the controls are to be resized as well, call the procedure to do that,
  1191.     then call the procedure to adjust the maximum and current values. Finally re-enable the controls
  1192.     by jamming a $FF in their contrlVis fields. */
  1193.  
  1194. void AdjustScrollbars(WindowPtr window, Boolean needsResize)
  1195. {
  1196.     DocumentPeek doc;
  1197.     
  1198.     doc = (DocumentPeek) window;
  1199.     /* First, turn visibility of scrollbars off so we won’t get unwanted redrawing */
  1200.     (*doc->docVScroll)->contrlVis = kControlInvisible;    /* turn them off */
  1201.     (*doc->docHScroll)->contrlVis = kControlInvisible;
  1202.     if ( needsResize )                                    /* move & size as needed */
  1203.         AdjustScrollSizes(window);
  1204.     AdjustScrollValues(window, needsResize);            /* fool with max and current value */
  1205.     /* Now, restore visibility in case we never had to ShowControl during adjustment */
  1206.     (*doc->docVScroll)->contrlVis = kControlVisible;    /* turn them on */
  1207.     (*doc->docHScroll)->contrlVis = kControlVisible;
  1208. } /* AdjustScrollbars */
  1209.  
  1210.  
  1211. /* Gets called from our assembly language routine, AsmClickLoop, which is in
  1212.     turn called by the TEClick toolbox routine. Saves the windows clip region,
  1213.     sets it to the portRect, adjusts the scrollbar values to match the TE scroll
  1214.     amount, then restores the clip region. */
  1215.  
  1216. #ifndef AUX
  1217.    pascal void PascalClickLoop()
  1218. #else
  1219.    void CClickLoop ()
  1220. #endif
  1221. {
  1222.     WindowPtr    window;
  1223.     RgnHandle    region;
  1224.     
  1225.     window = FrontWindow();
  1226.     region = NewRgn();
  1227.     GetClip(region);                    /* save clip */
  1228.     ClipRect(&window->portRect);
  1229.     AdjustScrollValues(window, true);    /* pass true for canRedraw */
  1230.     SetClip(region);                    /* restore clip */
  1231.     DisposeRgn(region);
  1232. } /* Pascal/C ClickLoop */
  1233.  
  1234.  
  1235. /* Gets called from our assembly language routine, AsmClickLoop, which is in
  1236.     turn called by the TEClick toolbox routine. It returns the address of the
  1237.     default clickLoop routine that was put into the TERec by TEAutoView to
  1238.     AsmClickLoop so that it can call it. */
  1239.  
  1240. #ifndef AUX
  1241.   pascal 
  1242. #endif
  1243. TEClickLoopUPP GetOldClickLoop()
  1244. {
  1245.     return ((DocumentPeek)FrontWindow())->docClick;
  1246. } /* GetOldClickLoop */
  1247.  
  1248.  
  1249. /*    Check to see if a window belongs to the application. If the window pointer
  1250.     passed was NIL, then it could not be an application window. WindowKinds
  1251.     that are negative belong to the system and windowKinds less than userKind
  1252.     are reserved by Apple except for windowKinds equal to dialogKind, which
  1253.     mean it is a dialog.
  1254.     1.02 - In order to reduce the chance of accidentally treating some window
  1255.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  1256.     is userKind. If you add different kinds of windows to Sample you'll need
  1257.     to change how this all works. */
  1258.  
  1259. Boolean IsAppWindow(WindowPtr window)
  1260. {
  1261.     short        windowKind;
  1262.  
  1263.     if ( window == nil )
  1264.         return false;
  1265.     else {    /* application windows have windowKinds = userKind (8) */
  1266.         windowKind = ((WindowPeek) window)->windowKind;
  1267.         return (windowKind == userKind);
  1268.     }
  1269. } /*IsAppWindow*/
  1270.  
  1271.  
  1272. /* Check to see if a window belongs to a desk accessory. */
  1273.  
  1274. Boolean IsDAWindow(WindowPtr window)
  1275. {
  1276.     if ( window == nil )
  1277.         return false;
  1278.     else    /* DA windows have negative windowKinds */
  1279.         return ((WindowPeek) window)->windowKind < 0;
  1280. } /*IsDAWindow*/
  1281.  
  1282.  
  1283. /*    Display an alert that tells the user an error occurred, then exit the program.
  1284.     This routine is used as an ultimate bail-out for serious errors that prohibit
  1285.     the continuation of the application. Errors that do not require the termination
  1286.     of the application should be handled in a different manner. Error checking and
  1287.     reporting has a place even in the simplest application. The error number is used
  1288.     to index an 'STR#' resource so that a relevant message can be displayed. */
  1289.  
  1290. void AlertUser(short error)
  1291. {
  1292.     short        itemHit;
  1293.     Str255        message;
  1294.  
  1295.     SetCursor(&qd.arrow);
  1296.     /* type Str255 is an array in MPW 3 */
  1297.     GetIndString(message, kErrStrings, error);
  1298.     ParamText(message, "", "", "");
  1299.     itemHit = Alert(rUserAlert, nil);
  1300. } /* AlertUser */
  1301.